package com.yy.micro.magic.core.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

 /**
   * @author YY
   * @version 1.0.0
   * @update 2021/9/19 10:01 下午
   * @description: 线程相关数据缓存，避免多线程时数据不一致问题。
 */
public final class ThreadContextHolder {

    private static ThreadLocal<Map<String,Object>> resources = new ThreadLocal<>();
    private static Logger logger = LoggerFactory.getLogger(ThreadContextHolder.class);

     /**
      * set value to thread local.
      * @param key
      * @param value
      */
    public static void set(String key,Object value){
        Map<String,Object> resource = resources.get();
        if (null == resource){
            resource = new HashMap<>();
            resources.set(resource);
        }
        if (resource.containsKey(key)){
            logger.debug("Override exists resource({}) in thread boot.", key);
        }
        resource.put(key,value);
        logger.debug("Bind resource to thread boot successfully, [key={},value={}]", key, value);
    }

     /**
      * get value form thread local.
      * @param key
      * @return
      */
    public static Object get(String key){
        Map<String,Object> resource = resources.get();
        if (null == resource || resource.isEmpty()){
            logger.debug("The resource is already unbind or not exists in thread boot,key={}", key);
            return null;
        }
        return resource.get(key);
    }

    /**
     * Unbind resource for given key from get thread
     *
     * @param key
     * @return
     */
    public static Object remove(Object key) {
        Object value;
        Map<String, Object> resourceMap = resources.get();
        if (resourceMap == null || resourceMap.size() == 0 || !resourceMap.containsKey(key)) {
            logger.debug("The resource is already unbind or not exists, key={}", key);
            return null;
        }
        value = resourceMap.remove(key);
        logger.debug("Remove resource from thread, [key={},value={}]", key, value);
        if (resourceMap.size() == 0) {
            resources.set(null);
        }
        return value;
    }

    /**
     * Check whether resource has bound
     *
     * @param key
     * @return
     */
    public static boolean isExists(String key) {
        Map<String, Object> resourceMap = resources.get();
        if (resourceMap == null || resourceMap.size() == 0 || !resourceMap.containsKey(key)) {
            return false;
        }
        return true;
    }

    /**
     * Clean all resource
     *
     */
    public static void clear() {
        resources.remove();
        logger.debug("Clear resources successfully.");
    }
}
